package com.exocr;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.ResponseResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraView;

import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class OCRCameraActivity extends CameraActivity {
    public interface OCRToakenCallBack{
        public void onResult(Object obj);
    }
    private static final int OCR_REQRUSET_CODE=1111;

    public static final String OcrTypeKey="ocrtype";
//    public static final String CallBackKey="callback";
    public static final String CachePathKey="cachePath";

    public static final String FullOCRUrlKey="fullocrurl";

    public static final String MASK_TYPE_ID_CARD_FRONT="MASK_TYPE_ID_CARD_FRONT";
    public static final String MASK_TYPE_ID_CARD_BACK="MASK_TYPE_ID_CARD_BACK";
    public static final String MASK_TYPE_BANK_CARD="MASK_TYPE_BANK_CARD";
    public static final String MASK_TYPE_PASSPORT="MASK_TYPE_PASSPORT";
//    public static final String maskKey="mask";
//    public static final String akKey="ak";
//    public static final String skKey="sk";
    public static OCR ocrInstance=null;
    public static AccessToken ocrToken=null;
    OCRTypes ocrType=null;
    String fullOCRUrl=null;

    String ocr_ak=null;
    String ocr_sk=null;

    String ocr_mask=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            createOCRInstance(this);
//            ocr_ak=getIntent().getStringExtra(akKey);
//            ocr_sk=getIntent().getStringExtra(skKey);
//            ocr_mask=getIntent().getStringExtra(maskKey);
            fullOCRUrl=getIntent().getStringExtra(FullOCRUrlKey);
            Serializable se=getIntent().getSerializableExtra(OcrTypeKey);
            if (se!=null&&se instanceof OCRTypes){
                ocrType=(OCRTypes)se;
                ocr_ak=ocrType.getApiKey();
                ocr_sk=ocrType.getApiSecretKey();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        super.onCreate(savedInstanceState);
    }
    public static void createOCRInstance(Context context){
        if (ocrInstance==null&&context!=null){
            ocrInstance=OCR.getInstance(context.getApplicationContext());
        }
    }
    public void initParamsIml() {
        if (OCRTypes.ocr_type_xunfei.equals(ocrType.getOcrType())){
            OCRCameraActivity.this.initParams();
        }else{
            initAccessToken(this,ocr_ak ,ocr_sk,new OCRToakenCallBack() {
                @Override
                public void onResult(final Object obj) {
                    OCRCameraActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (obj instanceof AccessToken){
                                try {
                                    OCRCameraActivity.this.initParams();
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }else{
                                Toast.makeText(OCRCameraActivity.this,"ocr 初始化失败",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            });
        }
    }
    //预留。为false的情况 意味着 license models so文件均可不需要，可减小apk
    boolean enableNativeIDCard=false;
    public void getIntentParams(){
        token = getIntent().getStringExtra(KEY_NATIVE_TOKEN);
        String cachePath=getIntent().getStringExtra(CachePathKey);
        if (TextUtils.isEmpty(cachePath)){
            cachePath= OCRCameraActivity.this.getCacheDir().getAbsolutePath();
        }
        if (!TextUtils.isEmpty(cachePath)){
            File directory = new File(cachePath);
            if (directory==null||!directory.exists()){
                directory.mkdirs();
            }
            String split="\\";
            if (cachePath.endsWith("\\")||cachePath.endsWith("/")){
                split="";
            }

            File file = new File(cachePath, split+"ocrfile.jpg");
            if (file.exists()){
                file.delete();
            }

            String ctype=ocrType.getCameraMaskType();
//            if (OCRTypes.ocr_type_common.equals(ocrType.getOcrType())){
//                ctype=CameraActivity.CONTENT_TYPE_GENERAL;
//            }else if (OCRTypes.ocr_type_card.equals(ocrType.getOcrType())){
//                if (OCRTypes.OCRCardBranch.type_idcard.equals(ocrType.getOcrBranch())){
//                    if (ocrType.getFrontOrBackType()==1){
//                        ctype=CameraActivity.CONTENT_TYPE_ID_CARD_BACK;
//                    }else{
//                        ctype=CameraActivity.CONTENT_TYPE_ID_CARD_FRONT;
//                    }
//                }else if (OCRTypes.OCRCardBranch.type_bankcard.equals(ocrType.getOcrBranch())){
//                    ctype=CameraActivity.CONTENT_TYPE_BANK_CARD;
//                }else if (OCRTypes.OCRCardBranch.type_passport.equals(ocrType.getOcrBranch())){
//                    ctype=CameraActivity.CONTENT_TYPE_PASSPORT;
//                }else{
//                    ctype=CameraActivity.CONTENT_TYPE_GENERAL;
//                }
//            }else if (OCRTypes.ocr_type_bill.equals(ocrType.getOcrType())){
//                ctype=CameraActivity.CONTENT_TYPE_GENERAL;
//            }else if (OCRTypes.ocr_type_car.equals(ocrType.getOcrType())){
//                ctype=CameraActivity.CONTENT_TYPE_GENERAL;
//            }else if (OCRTypes.ocr_type_educate.equals(ocrType.getOcrType())){
//                ctype=CameraActivity.CONTENT_TYPE_GENERAL;
//            }else if (OCRTypes.ocr_type_extra.equals(ocrType.getOcrType())){
//                ctype=CameraActivity.CONTENT_TYPE_GENERAL;
//            }else if (OCRTypes.ocr_type_xunfei.equals(ocrType.getOcrType())){
//                if (OCRTypes.OCRXFBranch.type_idcard.equals(ocrType.getOcrBranch())){
//                    if (ocrType.getFrontOrBackType()==1){
//                        ctype=CameraActivity.CONTENT_TYPE_ID_CARD_BACK;
//                    }else{
//                        ctype=CameraActivity.CONTENT_TYPE_ID_CARD_FRONT;
//                    }
//                }else if (OCRTypes.OCRXFBranch.type_bankcard.equals(ocrType.getOcrBranch())){
//                    ctype=CameraActivity.CONTENT_TYPE_BANK_CARD;
//                }else {
//                    ctype=CameraActivity.CONTENT_TYPE_GENERAL;
//                }
//            }
//            if (ocr_mask!=null&&ocr_mask instanceof String&&
//                    ctype.equals(CameraActivity.CONTENT_TYPE_GENERAL)){
//                if (ocr_mask.equals(MASK_TYPE_ID_CARD_FRONT)){
//                    ctype=CameraActivity.CONTENT_TYPE_ID_CARD_FRONT;
//                }else if (ocr_mask.equals(MASK_TYPE_ID_CARD_BACK)){
//                    ctype=CameraActivity.CONTENT_TYPE_ID_CARD_BACK;
//                }else if (ocr_mask.equals(MASK_TYPE_BANK_CARD)){
//                    ctype=CameraActivity.CONTENT_TYPE_BANK_CARD;
//                }else if (ocr_mask.equals(MASK_TYPE_PASSPORT)){
//                    ctype=CameraActivity.CONTENT_TYPE_PASSPORT;
//                }
//            }

//            if (!OCRTypes.OCRCardBranch.type_idcard.equals(ocrType.getOcrBranch())){
//                //非身份证识别无需为true，（避免使用身份mask时出现true的情况）
//                enableNativeIDCard=false;
//            }
            contentType=ctype;
            isNativeEnable=enableNativeIDCard;
            outputFile=file;
            if (OCRTypes.ocr_type_xunfei.equals(ocrType.getOcrType())){

            }else {
                if (isNativeEnable) {
                    initCameraNative(this);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (isNativeEnable){
            CameraNativeHelper.release();
        }
        super.onDestroy();
    }

    /**
     * 以license文件方式初始化
     */
    public static void initAccessToken(final Context context ,final String ocr_ak ,final String ocr_sk ,final OCRToakenCallBack callBack) {
        createOCRInstance(context);
        if (ocrToken==null){
            if (ocr_sk==null&&ocr_ak==null){
                ocrInstance.initAccessToken(new OnResultListener<AccessToken>() {
                    @Override
                    public void onResult(AccessToken accessToken) {
                        ocrToken=accessToken;
                        if (callBack!=null){
                            callBack.onResult(accessToken);
                        }
                    }

                    @Override
                    public void onError(OCRError error) {
                        error.printStackTrace();
                        if (callBack!=null){
                            callBack.onResult(error);
                        }
                    }
                }, context.getApplicationContext());
            }else if (!TextUtils.isEmpty(ocr_ak)&&!TextUtils.isEmpty(ocr_sk)){
                ocrInstance.initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
                    @Override
                    public void onResult(AccessToken accessToken) {
                        ocrToken=accessToken;
                        if (callBack!=null){
                            callBack.onResult(accessToken);
                        }
                    }

                    @Override
                    public void onError(OCRError ocrError) {
                        if (callBack!=null){
                            callBack.onResult(ocrError);
                        }
                    }
                },context,ocr_ak,ocr_sk);
            }
        }else{
            callBack.onResult(ocrToken);
        }
    }
    private void initCameraNative(final Context context) {
        if (TextUtils.isEmpty(token)){
            token=ocrInstance.getLicense();
        }
        CameraNativeHelper.init(context, token,
            new CameraNativeHelper.CameraNativeInitCallback() {
                @Override
                public void onError(int errorCode, Throwable e) {
                    String msg;
                    switch (errorCode) {
                        case CameraView.NATIVE_SOLOAD_FAIL:
                            msg = "加载so失败，请确保apk中存在ui部分的so";
                            break;
                        case CameraView.NATIVE_AUTH_FAIL:
                            msg = "授权本地质量控制token获取失败";
                            break;
                        case CameraView.NATIVE_INIT_FAIL:
                            msg = "本地质量控制";
                            break;
                        default:
                            msg = String.valueOf(errorCode);
                    }
                    if (e!=null&&e.getLocalizedMessage()!=null){
                        Log.i("OCRActivity",e.getLocalizedMessage());
                    }else{
                        Log.i("OCRActivity",msg);
                    }
                }
            });
    }
    public void callBackFunc(Object obj){
        if (obj!=null) {
            Intent it=null;
            int result_flag=RESULT_OK;
            if (obj instanceof ResponseResult) {
                ResponseResult rr = (ResponseResult) obj;
                it=new Intent();
                it.putExtra("result",rr.getJsonRes());
            } else if (obj instanceof OCRError) {
                result_flag=RESULT_CANCELED;
                OCRError rr = (OCRError) obj;
                it=new Intent();
                it.putExtra("result",rr);
            } else if (obj instanceof Map) {
                it=new Intent();
                JSONObject jsonObj=new JSONObject((Map)obj);
                it.putExtra("result",jsonObj.toString());
            }
            if (it!=null){
                it.putExtra(OcrTypeKey,ocrType);
                if (outputFile!=null&& outputFile.exists()) {
                    String filePath = outputFile.getAbsolutePath();
                    it.putExtra("filePath",filePath);
                }

                setResult(result_flag,it);
            }
        }
        if (alertDialog!=null){
            alertDialog.dismiss();
        }
        finish();
    }
    private static Handler handler=new Handler(Looper.getMainLooper());
    AlertDialog alertDialog=null;
    public void callORC(){
        if (outputFile!=null&& outputFile.exists()) {
            String filePath = outputFile.getAbsolutePath();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示").setMessage("正在处理中...");
            alertDialog=builder.create();
            alertDialog.show();
            doOCR(this, ocrType, filePath, fullOCRUrl, ocr_ak, ocr_sk, new OCRCallBack() {
                @Override
                public void result(Object data) {
                    callBackFunc(data);
                }
            });
        }
    }
    public void callFinishActivity(){
        handler.post(new Runnable() {
            public void run() {
                callORC();
            }
        });
    }
    //filePath 图片绝对路径
    //fullOCRUrl 可为空
    //百度ocr需要 ocr_ak  ocr_sk
    public static void doOCR(Context context,final OCRTypes ocrType,final String filePath,final String fullOCRUrl,final String ocr_ak ,final String ocr_sk,final OCRCallBack callBack){
        if (OCRTypes.ocr_type_xunfei.equals(ocrType.getOcrType())){
            XFOCRHelper.doOCR(fullOCRUrl,ocrType,filePath,callBack);
        }else {
            initAccessToken(context, ocr_ak, ocr_sk, new OCRToakenCallBack() {
                @Override
                public void onResult(Object obj) {
                    if (obj instanceof AccessToken){
                        OCRHelper.doOCR(ocrInstance, fullOCRUrl, ocrType, filePath, callBack);
                    }else{
                        //obj is OCRError
                        if (callBack!=null){
                            callBack.result(obj);
                        }
                    }
                }
            });

        }
    }
}